package com.hariro.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hariro.adapter.SortNavAdpater;
import com.hariro.adapter.SortTabAdapter;
import com.hariro.bean.SortTab;
import com.hariro.helper.JsonHelper;
import com.hariro.url.NewFashionUrl;
import com.qianfeng.project.R;

public class Search_Fragment extends Fragment implements OnItemClickListener,
		OnClickListener {

	private static final String TAG = "SearchFragment";

	/** 左侧分类导航条的ListView */
	private ListView lv_searchFragment_sortNavList;

	/** 一组未处于焦点的图片的id */
	private int[] noFocusIconIds;

	/** 一组处于焦点的图片的id */
	private int[] focusedIconIds;

	/** 从资源文件arrays中获得导航条名字的数组 */
	String[] sortNavNames;

	/** 用于存放所有的分类导航条的Tab标签 */
	private Map<Integer, View> sorNavItemViews;

	/** 用来记住前一个点击的分类导航标签的位置 */
	private int previousTabPosition;

	/** 右侧导航标签的ListView */
	private ListView lv_searchFragment_sortTab;

	/** volley框架，文本下载器 */
	private RequestQueue requestQueue = null;

	/** 所有左侧分类导航的url */
	private String[] sortNavUrls;
	private LinearLayout linearLayout_searchPage;

	private SharedPreferences sharedPreferences;

	private List[] sortTabLists;

	private Handler handler;

	private SortTabAdapter[] sortTabAdapters;
	private int[] termIds;
	private int termId;
	private String tagId;
	private TextView tv_titleBack;
	private LinearLayout ll_refresh;
	private String sortTag;
	private StringBuilder tagUrl;

	private FragmentManager fragmentManager;

	// 初始化数据
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		noFocusIconIds = new int[] {
				R.drawable.adapter_home_menu_left_remen_up,
				R.drawable.adapter_home_menu_left_shangyi_up,
				R.drawable.adapter_home_menu_left_kuzi_up,
				R.drawable.adapter_home_menu_left_qunzi_up,
				R.drawable.adapter_home_menu_left_xiezi_up,
				R.drawable.adapter_home_menu_left_baobao_up,
				R.drawable.adapter_home_menu_left_peishi_up };
		focusedIconIds = new int[] {
				R.drawable.adapter_home_menu_left_remen_down,
				R.drawable.adapter_home_menu_left_shangyi_down,
				R.drawable.adapter_home_menu_left_kuzi_down,
				R.drawable.adapter_home_menu_left_qunzi_down,
				R.drawable.adapter_home_menu_left_xiezi_down,
				R.drawable.adapter_home_menu_left_baobao_down,
				R.drawable.adapter_home_menu_left_peishi_down };
		sortNavUrls = new String[] { NewFashionUrl.HOT_SORTNAV,
				NewFashionUrl.SHANGYI_SORTNAV, NewFashionUrl.KUZI_SORTNAV,
				NewFashionUrl.QUNZI_SORTNAV, NewFashionUrl.XIEZI_SORTNAV,
				NewFashionUrl.BAOBAO_SORTNAV, NewFashionUrl.PEISHI_SORTNAV };

		sorNavItemViews = new HashMap<Integer, View>();
		sharedPreferences = this.getActivity().getSharedPreferences(
				"sortTagJson", Context.MODE_PRIVATE);
		sortTabLists = new List[focusedIconIds.length];
		sortTabAdapters = new SortTabAdapter[focusedIconIds.length];
		termIds = new int[] { 0, 6, 5, 3, 81, 141, 296 };
		termId = 0;
		tagUrl = new StringBuilder();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View searchView = inflater.inflate(R.layout.fragment_search, null);

		linearLayout_searchPage = (LinearLayout) searchView
				.findViewById(R.id.linearLayout_searchPage);
		tv_titleBack = (TextView) searchView
				.findViewById(R.id.textView_search_title);
		linearLayout_searchPage = (LinearLayout) searchView
				.findViewById(R.id.linearLayout_searchPage);
		tv_titleBack = (TextView) searchView
				.findViewById(R.id.textView_search_title);
		linearLayout_searchPage = (LinearLayout) searchView
				.findViewById(R.id.linearLayout_searchPage);
		tv_titleBack = (TextView) searchView
				.findViewById(R.id.textView_search_title);
		linearLayout_searchPage = (LinearLayout) searchView
				.findViewById(R.id.linearLayout_searchPage);
		tv_titleBack = (TextView) searchView
				.findViewById(R.id.textView_search_title);
		linearLayout_searchPage = (LinearLayout) searchView
				.findViewById(R.id.linearLayout_searchPage);
		tv_titleBack = (TextView) searchView
				.findViewById(R.id.textView_search_title);

		tv_titleBack.setOnClickListener(this);
		ll_refresh = (LinearLayout) searchView.findViewById(R.id.ll_refresh);
		ll_refresh.setOnClickListener(this);
		lv_searchFragment_sortNavList = (ListView) searchView
				.findViewById(R.id.lv_searchFragment_sortNavList);

		// 设置分类导航条ListView的属性
		setListViewPro();

		// 给listView的第一个item设置为焦点状态
		View headView = lv_searchFragment_sortNavList.getAdapter().getView(0,
				null, lv_searchFragment_sortNavList);
		setFocusTabStyle(headView);

		// 右侧分类标签
		lv_searchFragment_sortTab = (ListView) searchView
				.findViewById(R.id.lv_searchFragment_sortTab);
		lv_searchFragment_sortTab
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
					}
				});
		lv_searchFragment_sortTab.setEmptyView(searchView
				.findViewById(R.id.iv_listviewEmpty));
		handler = new Handler() {
			@Override
			public void handleMessage(final Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				SortTabAdapter sortTabAdapter = new SortTabAdapter(
						getActivity(), sortTabLists[msg.what]) {

					@Override
					public View initView1(final int position, View convertView,
							ViewGroup parent, final List<SortTab> list) {
						ViewHolder viewHolder = null;
						if (convertView == null) {
							viewHolder = new ViewHolder();
							convertView = View.inflate(getActivity(),
									R.layout.gridview_item_sorttab, null);
							viewHolder.imageView = (ImageView) convertView
									.findViewById(R.id.iv_grideview_item);
							viewHolder.textView = (TextView) convertView
									.findViewById(R.id.tv_grideview_item);
							convertView.setTag(viewHolder);
						} else {
							viewHolder = (ViewHolder) convertView.getTag();
						}
						SortTab sortTab = list.get(position);
						viewHolder.textView.setText(sortTab.getTagName());
						viewHolder.imageView.setImageResource(imageIds[Integer
								.parseInt(sortTab.getFlag())]);
						viewHolder.imageView
								.setOnClickListener(new OnClickListener() {

									@Override
									public void onClick(View v) {
										linearLayout_searchPage
												.setVisibility(View.GONE);
										tv_titleBack.setText("<      "
												+ list.get(position)
														.getTagName());
										tagId = list.get(position).getTagId();
										CommodityFragment commodityFragment = new CommodityFragment();
										Bundle bundle = new Bundle();
										HashMap<String, Object> map = new HashMap<String, Object>();
										map.put("tagId", tagId);
										map.put("termId", termId);
										map.put("tv_titleBack", tv_titleBack);
										bundle.putSerializable("msg", map);
										;
										commodityFragment.setArguments(bundle);
										fragmentManager = getActivity()
												.getSupportFragmentManager();
										FragmentTransaction fragmentTransaction = fragmentManager
												.beginTransaction();
										// fragmentTransaction.hide(SearchFragment.this).add(R.id.linearLayout_commodityContainer,
										// commodityFragment,"CommodityFragment").show(commodityFragment);
										fragmentTransaction
												.replace(
														R.id.linearLayout_commodityContainer,
														commodityFragment,
														"CommodityFragment");
										// fragmentTransaction.addToBackStack(null);
										fragmentTransaction.commit();
										tv_titleBack.setClickable(true);
										ll_refresh.setVisibility(View.VISIBLE);
										ll_refresh.setClickable(true);
										sortTag = list.get(position)
												.getTagName();
									}
								});
						return convertView;
					}

					class ViewHolder {
						private ImageView imageView;
						private TextView textView;
					}

				};
				lv_searchFragment_sortTab.setAdapter(sortTabAdapter);
				sortTabAdapters[msg.what] = sortTabAdapter;
			}

		};

		// 开始网络加载导航标签的json字符串加载
		Log.i(TAG, "--开始网络加载导航标签的json字符串加载");
		loadSortTabJsonFromWeb(0);
		loadSortTabJsonFromWeb(1);
		loadSortTabJsonFromWeb(2);
		loadSortTabJsonFromWeb(3);
		loadSortTabJsonFromWeb(4);
		loadSortTabJsonFromWeb(5);
		loadSortTabJsonFromWeb(6);

		return searchView;
	}

	// 网络加载json数据
	public void loadSortTabJsonFromWeb(final int position) {
		final Message message = handler.obtainMessage();
		message.what = position;
		requestQueue = Volley.newRequestQueue(this.getActivity());
		StringRequest sortNavJsonRequest = new StringRequest(
				sortNavUrls[position], new Listener<String>() {

					@Override
					public void onResponse(String response) {
						Log.i(TAG, "-@-网络加载[" + sortNavNames[position]
								+ "]导航的json");
						sortTabLists[position] = JsonHelper
								.sortTabJsonToList(response);
						if (position == previousTabPosition) {
							Log.i(TAG, "-@-第一次通知的是[" + sortNavNames[position]
									+ "]导航");
							handler.sendMessage(message);
						}
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.i(TAG, "获取分类导航条的json失败");
					}
				});
		requestQueue.add(sortNavJsonRequest);
	}

	// 根据position下载右侧导航标签的json数据
	public void loadJsonSetAdapter(final int position) {

		final Message message = handler.obtainMessage();
		message.what = position;
		if (sortTabAdapters[position] != null) {
			Log.i(TAG, "--找到对应的SortTabAdapter，重复利用");
			lv_searchFragment_sortTab.setAdapter(sortTabAdapters[position]);
		} else if (sortTabLists[position] != null) {
			Log.i(TAG, "--找到对应的导航标签的Json，重复利用");
			handler.sendMessage(message);
		}
	}

	/**
	 * 改变处于焦点的Tab标签的样式
	 */
	public void setFocusTabStyle(View focusView) {
		focusView.setBackgroundColor(Color.parseColor("#E8E8E8"));
		ImageView focusImageView = (ImageView) focusView
				.findViewById(R.id.iv_sortNav_Icon);
		TextView focusTextView = (TextView) focusView
				.findViewById(R.id.tv_sortNav_name);
		focusImageView.setImageResource(focusedIconIds[(Integer) focusView
				.getTag()]);
		focusTextView.setTextColor(Color.parseColor("#30CCF8"));

		// 把修改后的view存入分类导航条容器sorNavItemViews
		sorNavItemViews.put((Integer) focusView.getTag(), focusView);

		// 记住当前所点击的Tab的位置
		previousTabPosition = (Integer) focusView.getTag();

		termId = termIds[(Integer) focusView.getTag()];
	}

	/**
	 * 改变不处于焦点的Tab标签的样式*
	 */
	public void setNoFocusTabStyle() {
		View noFocusView = sorNavItemViews.get(previousTabPosition);
		noFocusView.setBackgroundColor(Color.parseColor("#202420"));
		ImageView noFocusImageView = (ImageView) noFocusView
				.findViewById(R.id.iv_sortNav_Icon);
		TextView noFocusTextView = (TextView) noFocusView
				.findViewById(R.id.tv_sortNav_name);
		noFocusImageView.setImageResource(noFocusIconIds[(Integer) noFocusView
				.getTag()]);
		noFocusTextView.setTextColor(Color.parseColor("#DDDDDD"));
		// 把修改后的view存入分类导航条容器sorNavItemViews
		sorNavItemViews.put((Integer) noFocusView.getTag(), noFocusView);
	}

	/**
	 * 设置分类导航ListView的适配器，单击监听器
	 */
	private void setListViewPro() {
		// 设置适配器
		lv_searchFragment_sortNavList.setAdapter(new SortNavAdpater(
				getSortTabList()) {
			@Override
			public View initialiseView(int position, View convertView,
					ViewGroup parent, List<Map<String, Object>> dataList) {
				if (sorNavItemViews.get(position) == null) {
					Log.i(TAG, "--从分类导航标签容器里没有找到" + position + "位置上的标签，开始创建！");
					View view = View.inflate(getActivity(),
							R.layout.listview_item_sortnav, null);
					view.setBackgroundColor(Color.parseColor("#202420"));
					;
					ImageView iv_sortNav_Icon = (ImageView) view
							.findViewById(R.id.iv_sortNav_Icon);
					TextView tv_sortNav_name = (TextView) view
							.findViewById(R.id.tv_sortNav_name);
					iv_sortNav_Icon.setImageResource((Integer) dataList.get(
							position).get("sortNavIco"));
					tv_sortNav_name.setText(dataList.get(position)
							.get("sortNavName").toString());

					// 给每个view设置对于的位置position标签
					view.setTag(position);

					// 把每次的分类导航标签放入map中
					sorNavItemViews.put(position, view);
					return view;
				} else {
					Log.i(TAG, "--从分类导航标签容器里找到了" + position + "位置上的标签，直接使用！");
					return sorNavItemViews.get(position);
				}
			}
		});
		lv_searchFragment_sortNavList.setOnItemClickListener(this);

	}

	/**
	 * 处理分类导航条ListView的item的单击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		setNoFocusTabStyle();
		if (previousTabPosition != position) {
			loadJsonSetAdapter(position);
		} else {
			Toast.makeText(getActivity(), "你点击的导航已经处于焦点" + previousTabPosition,
					0).show();
		}
		setFocusTabStyle(view);

	}

	/**
	 * 获得分类导航条的List<Map<String,Object>>集合
	 */
	private List<Map<String, Object>> getSortTabList() {
		sortNavNames = this.getActivity().getResources()
				.getStringArray(R.array.sortNavNames);

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < sortNavNames.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sortNavIco", noFocusIconIds[i]);
			map.put("sortNavName", sortNavNames[i]);
			list.add(map);
		}
		return list;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textView_search_title:
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			if (tv_titleBack.getText().toString().trim().contains("宝贝详情")) {
				Fragment shopFragment = fragmentManager
						.findFragmentByTag("ShopFragment");
				CommodityFragment commodityFragment = (CommodityFragment) fragmentManager
						.findFragmentByTag("CommodityFragment");
				if (shopFragment != null) {
					fragmentTransaction.remove(shopFragment);
					commodityFragment.view.setVisibility(View.VISIBLE);
					tv_titleBack.setText("< " + sortTag);
				}
			} else {
				fragmentTransaction.remove(
						fragmentManager.findFragmentByTag("CommodityFragment"))
						.commit();
				tv_titleBack.setText("搜索");
				tv_titleBack.setClickable(false);
				ll_refresh.setVisibility(View.GONE);
				ll_refresh.setClickable(false);
				linearLayout_searchPage.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.ll_refresh:
			Toast.makeText(getActivity(), "我执行啦", 0).show();
			if (tagUrl != null && !tagUrl.equals("")) {
				CommodityFragment commodityFragment = (CommodityFragment) fragmentManager
						.findFragmentByTag("CommodityFragment");
				commodityFragment.first_commodityList.removeAllViews();
				commodityFragment.second_commodityList.removeAllViews();
				int d = commodityFragment.page;
				for (int i = 0; i <= commodityFragment.page; i++) {
					tagUrl.delete(0, tagUrl.length());
					tagUrl.append("http://mobileapi.j.cn/?method=listv4&first=0&start="
							+ (i * 10)
							+ "&count=10&uid=&imgSize=mid2&longitude=4.9E-324&latitude=4.9E-324&thisTime=1408342034&lastTime=1408341124&freshRecord=YFDxU48%3D%0A&v=2.0&termId="
							+ termId
							+ "&pid="
							+ tagId
							+ "&tid=&shopId=&net=wifi");
					commodityFragment.loadCommodityJson(tagUrl.toString());
					Log.i(TAG, "@@正在加载中:" + tagUrl.toString());
				}
			}
			break;
		}
	}
}
